// 引入模块
const Sequelize = require('sequelize')

// 读取配置
const mysqlConfig = require('../configs/mysql-config')

// 根据配置实例化seq
var seq = new Sequelize(
  mysqlConfig.dbname,
  mysqlConfig.uname,
  mysqlConfig.upwd,
  {
    host: mysqlConfig.host,
    dialect: mysqlConfig.dialect,
    pool: mysqlConfig.pool
  }
)

// console.log(User)
/**
 * 定义数据模型
 *
 * @param {any} name 模型名称【数据库表名】
 * @param {any} attributes 数据字段集合
 * @returns 数据模型对象
 */
function defineModel(name, attributes) {
  var attrs = {}

  for (let key in attributes) {
    let value = attributes[key]
    if (typeof value === 'object' && value['type']) {
      value.allowNull = value.allowNull || false
      attrs[key] = value
    } else {
      attrs[key] = {
        type: value,
        allowNull: false
      }
    }
  }
  // 调用seq的方法定义模型并返回
  return seq.define(name, attrs, {
    tableName: name,
    timestamps: false
  })
}
const UserModel = defineModel(
  'login',
  {
    nickname: Sequelize.STRING,
    password: Sequelize.STRING,
    userid: Sequelize.STRING,
    rolename: Sequelize.STRING,
    role_id: Sequelize.STRING,
    avatar: { type: Sequelize.STRING, allowNull: true },
    email: Sequelize.STRING,
    collect: { type: Sequelize.STRING, allowNull: true },
    borrow: { type: Sequelize.STRING, allowNull: true },
    mybooks: { type: Sequelize.STRING, allowNull: true },
    registerdate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
  },
  {
    tableName: 'login'
  }
)
const BooksModel = defineModel(
  'bookslist',
  {
    bookId: Sequelize.STRING,
    bookName: Sequelize.STRING,
    bookImage: { type: Sequelize.STRING, allowNull: true },
    author: Sequelize.STRING,
    bookVersion: Sequelize.STRING,
    bookPress: Sequelize.STRING,
    bookDescribe: Sequelize.STRING,
    tags: Sequelize.STRING,
    classify: Sequelize.STRING,
    collectNum: { type: Sequelize.STRING, defaultValue: 0 },
    borrowNum: { type: Sequelize.STRING, defaultValue: 0 },
    status: { type: Sequelize.STRING, defaultValue: 'pending' },
    uploadDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },
    inventory: { type: Sequelize.STRING, defaultValue: 1 },
    userId: Sequelize.STRING
  },
  {
    tableName: 'bookslist'
  }
)
module.exports = { UserModel, BooksModel }
// exports.defineModel = defineModel
